package com.bootdo.wx.controller;

import com.bootdo.common.domain.Tree;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.UserExcelUtils;
import com.bootdo.wx.dao.OrderComDao;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户,会员
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-05-22 15:32:07
 */
 
@Controller
@RequestMapping("/wx/memberUser")
public class MemberUserController {
	@Autowired
	private MemberUserService memberUserService;
	@Autowired
	private OrderComService orderComService;
	@Autowired
	private MemberScoreService memberScoreService;
	@Autowired
	private MemberCouponService memberCouponService;
	@Autowired
	private SalesCouponService salesCouponService;
	@Autowired
	private OrderOrderService orderOrderService;
	@Autowired
	private MemberStockService memberStockService;
	@Autowired
	private OrderComDao orderComDao;
	
	@GetMapping("/{flag}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String MemberUser(@PathVariable("flag") String flag,Model model){
		model.addAttribute("level", flag);
		model.addAttribute("num", flag); // 传入JS页面判断是否隐藏:可用,冻结,已返三列字段
	    return "wx/memberUser/memberUser";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils list(@RequestParam Map<String, Object> params){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		//查询列表数据
        Query query = new Query(params);
        if(params.containsKey("name")&&params.get("name")!=null&&!"".equals(params.get("name").toString())){
        	List<MemberUserDO> memberUserList = memberUserService.likeList(query);
        	//int count = memberUserService.count(params);
        	for (MemberUserDO memberUserDO : memberUserList) {
    			Map<String,Object> map = new HashMap<String,Object>();
    			map.put("userId", memberUserDO.getId());
    			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
    			memberUserDO.setMoney(new BigDecimal(moneyMap.get("canExPrice").toString()));
    			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);

				BigDecimal freeze = new BigDecimal(0); //冻结金额
				freeze = freeze.add(orderComDao.frozen(map));
				memberUserDO.setFreeze(freeze);
				BigDecimal onceMoney = new BigDecimal(0); //已反余额
				onceMoney = onceMoney.add(orderOrderService.onceUseMoney(map));

				Map<String,Object> userMap = StringUtils.entityToMap(memberUserDO);
				userMap.put("shoppingNum", shoppingNum);
    			/*BigDecimal scoreNumber = memberScoreService.getSumByUser(map);
    			userMap.put("scoreNum", scoreNumber); */  //积分
				userMap.put("onceMoney",onceMoney);//已反余额
				list.add(userMap);
    		}
        	int count = memberUserService.likeCount(params);
    		PageUtils pageUtils = new PageUtils(list, count);
    		return pageUtils;
        }
		List<MemberUserDO> memberUserList = memberUserService.list(query);
		int count = memberUserService.count(params);
		for (MemberUserDO memberUserDO : memberUserList) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", memberUserDO.getId());
			Map<String,Object> moneyMap = orderComService.getMemberCom(map);
			memberUserDO.setMoney(new BigDecimal(moneyMap.get("canExPrice").toString()));
			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);

			BigDecimal freeze = new BigDecimal(0); //冻结金额
			BigDecimal onceMoney = new BigDecimal(0); //已反余额
			freeze = freeze.add(orderComDao.frozen(map));
			onceMoney = onceMoney.add(orderOrderService.onceUseMoney(map));
			memberUserDO.setFreeze(freeze);

			Map<String,Object> userMap = StringUtils.entityToMap(memberUserDO);
			userMap.put("shoppingNum", shoppingNum);
			/*BigDecimal scoreNumber = memberScoreService.getSumByUser(map);
			userMap.put("scoreNum", scoreNumber);   //积分*/
			userMap.put("onceMoney",onceMoney);//已反余额
			list.add(userMap);
		}
		PageUtils pageUtils = new PageUtils(list, count);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:memberUser:add")
	String add(){
	    return "wx/memberUser/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:memberUser:edit")
	String edit(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		model.addAttribute("memberUser", memberUser);
	    return "wx/memberUser/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:memberUser:add")
	public R save( MemberUserDO memberUser){
		memberUser.setId(UUIDUtils.getUUID());
		if(memberUser.getPhone()==null||"".equals(memberUser.getPhone())){
			return R.error("手机号为必填项");
		}
		MemberUserDO findByPhone = memberUserService.findByPhone(memberUser.getPhone());
		if(findByPhone!=null){
			return R.error("已添加过这个手机号!");
		}
		memberUser.setDisabled(1);
		memberUser.setLevel(3);
		if(memberUserService.save(memberUser)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:memberUser:edit")
	public R update( MemberUserDO memberUser){
		MemberUserDO memberUserDO = memberUserService.get(memberUser.getId());
		MemberUserDO memberUserDO1 = memberUserService.get(memberUserDO.getIntroUser());
		if(null!=memberUserDO1&&memberUserDO1.getIntroUser().equals(memberUser.getId())){
			return R.error("不能相互上级");

		}
		if(null!=memberUserDO1&&memberUserDO.getIntroUser().equals(memberUserDO.getId())){
			return R.error("不能设置自己为自己的上级");
		}
		memberUserDO.setIntroUser(memberUser.getIntroUser());
		memberUserDO.setUpdateAt(new Date());
		memberUserService.update(memberUserDO);

		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:memberUser:remove")
	public R remove( String id){
		if(memberUserService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:memberUser:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		memberUserService.batchRemove(ids);
		return R.ok();
	}

	/*
	* 个人业绩图表
	* */
	@RequestMapping( "/monthMoneyEcharts")
	@ResponseBody
	public R monthMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.getOrderEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal[] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("y").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month",month).put("number",number).put("money", money);
	}

	/*
	* 平台业绩图表
	* */
	@RequestMapping( "/allMoneyEcharts")
	@ResponseBody
	public R allMoneyEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allMoneyEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		BigDecimal [] money = new BigDecimal[12];
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			month[i] = map.get("month").toString();
			number[i] = Integer.valueOf(map.get("number").toString());
			money[i] = new BigDecimal(map.get("money").toString());
		}
		return R.ok().put("month", month).put("number",number).put("money", money);
	}

	/*
	* 平台会员人数图表
	* */
	@RequestMapping( "/allUserEcharts")
	@ResponseBody
	public R allUserEcharts(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allUserEcharts(params);
		String [] month = new String[12];
		int [] number = new int[12];
		int [] number0 = new int[12];
		int [] number1 = new int[12];
		int [] number2 = new int[12];
		int [] number3 = new int[12];
		int [] number4 = new int[12];
		int j =0;
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			if(!ArrayUtils.contains(month,map.get("month").toString())){
				month[j] = map.get("month").toString();
				j++;
			}
			//number[i] = Integer.valueOf(map.get("number").toString());
			if(map.get("level")!=null&&!"".equals(map.get("level").toString())){
				if(j>0){
					j--;
				}
						String level = map.get("level").toString();
						switch(level){
						    case "0" :
						       //语句
						    	number0[j]= Integer.valueOf(map.get("number").toString());
						    	j++;
						    	break; //可选
							case "1" :
							   //语句
								number1[j]= Integer.valueOf(map.get("number").toString());
								j++;
							    break; //可选
							case "2" :
								//语句
								number2[j]= Integer.valueOf(map.get("number").toString());
								j++;
								break; //可选
							case "3" :
								//语句
								number3[j]= Integer.valueOf(map.get("number").toString());
								j++;
								break; //可选
							/*case "-1" :
								//语句
								number3[j]= Integer.valueOf(map.get("number").toString());
								j++;
								break; //可选*/
							case "-2" :
								//语句
								number4[j]= Integer.valueOf(map.get("number").toString());
								j++;
								break; //可选
							//你可以有任意数量的case语句
							default : //可选
							   //语句
								j++;
								break ;
							}

			}
			
		}
		return R.ok().put("month",month).put("number", number).put("number0", number0).put("number1", number1).put("number2", number2).put("number3", number3).put("number4", number4);
	}
	/*
	 * 当日会员人数图表
	 * */
	@RequestMapping( "/allUserEchartsByToday")
	@ResponseBody
	public R allUserEchartsByToday(@RequestParam Map<String,Object> params){
		List<Map<String,Object>> list = memberUserService.allUserEchartsByToday(params);
		String [] date = new String[7];
		int [] number = new int[7];
		int [] number0 = new int[7];
		int [] number1 = new int[7];
		int [] number2 = new int[7];
		int [] number3 = new int[7];
		int [] number4 = new int[7];
		int [] number5 = new int[7];
		BigDecimal [] number6 = new BigDecimal[7];
		int j =0;
		for (int i=0; i<list.size(); i++) {
			Map<String,Object> map = list.get(i);
			if(!ArrayUtils.contains(date,map.get("date").toString())){
				date[j] = map.get("date").toString();
				j++;
			}
			number5[i]=Integer.valueOf(map.get("orderNum").toString());
			number6[i]=new BigDecimal(map.get("orderMoney").toString());
			//number[i] = Integer.valueOf(map.get("number").toString());
			if(map.get("level")!=null&&!"".equals(map.get("level").toString())){
				if(j>0){
					j--;
				}
				String level = map.get("level").toString();
				switch(level){
				case "0" :
					//语句
					number0[j]= Integer.valueOf(map.get("number").toString());
					j++;
					break; //可选
				case "1" :
					//语句
					number1[j]= Integer.valueOf(map.get("number").toString());
					j++;
					break; //可选
				case "2" :
					//语句
					number2[j]= Integer.valueOf(map.get("number").toString());
					j++;
					break; //可选
					case "3" :
						//语句
						number3[j]= Integer.valueOf(map.get("number").toString());
						j++;
						break; //可选
				/*case "-1" :
					//语句
					number3[j]= Integer.valueOf(map.get("number").toString());
					j++;
					break; //可选*/
				case "-2" :
					//语句
					number4[j]= Integer.valueOf(map.get("number").toString());
					j++;
					break; //可选
					//你可以有任意数量的case语句
				default : //可选
					//语句
					j++;
					break ;
				}
				
			}
			
		}
		return R.ok().put("date",date).put("number", number).put("number0", number0).put("number1", number1).put("number2", number2).put("number3", number3).put("number4", number4).put("number5", number5).put("number6", number6);
	}


	/*
	 * 后台查询余额
	 * status: 0：可用余额，1：冻结余额 2:已余额
	 * */
	@GetMapping("/goMoneyList/{id}/{status}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String goMoneyList(@PathVariable("id") String id,@PathVariable("status") String status,Model model){
		model.addAttribute("userId", id);
        model.addAttribute("status", status);
		return "wx/memberUser/money";
	}

	/*
	 * 后台查询余额列表
	 * */
	@ResponseBody
	@GetMapping("/getMoneyList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getMoneyList(@RequestParam Map<String, Object> params){
		//查询余额列表
		Query query = new Query(params);
		List<Map<String,Object>> list = memberUserService.getMoneyListByUser(query);
		if(list.size()>0){
			for (Map<String, Object> map : list) {
				if(null!=map.get("order_sn")&&!"".equals(map.get("order_sn"))){
					OrderOrderDO byOrder = orderOrderService.getByOrder(map.get("order_sn").toString());
					if(byOrder!=null){
						MemberUserDO memberUserDO = memberUserService.get(byOrder.getUserId());
						if(memberUserDO!=null){
							map.put("userName", memberUserDO.getName());
							map.put("level", memberUserDO.getLevel());
							MemberUserDO memberUserDO2 = memberUserService.get(memberUserDO.getIntroUser());
							if(memberUserDO2!=null){
								map.put("upName", memberUserDO2.getName());
							}else{
								map.put("upName", "");
							}
						}
				}
				
					
				}else{
					MemberUserDO memberUserDO = memberUserService.get(params.get("userId").toString());
					MemberUserDO memberUserDO2 = memberUserService.get(memberUserDO.getIntroUser());
					map.put("userName", memberUserDO.getName());
					map.put("level", memberUserDO.getLevel());
					map.put("upName", memberUserDO2.getName());
				}
			}
		}
		int total = memberUserService.getMoneyListByUserCount(params);
		PageUtils pageUtils = new PageUtils(list, total);
		return pageUtils;
	}

	/**
	 * 导出余额记录excel表格
	 */
	@RequestMapping( "/getmoneyExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getmoneyExcel(@RequestParam() Map<String,Object> params,
							  HttpServletResponse response,HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getMoneyListByUser(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"余额变动记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.exportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/*
	* 得到直推人信息
	* */
	@GetMapping("/getFather/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String getFather(@PathVariable("id") String id,Model model){
		MemberUserDO memberUser = memberUserService.get(id);
		MemberUserDO fatherUser = memberUserService.get(memberUser.getIntroUser());
		if (fatherUser == null) {
			fatherUser = new MemberUserDO();
		}
		model.addAttribute("fatherUser", fatherUser);
		model.addAttribute("userId", id);
		return "wx/memberUser/getFather";
	}
	/*
	 * 得到直接代理信息
	 * */
	@GetMapping("/getUpUser/{id}")
	@RequiresPermissions("wx:memberUser:memberUser")
	String getUpUser(@PathVariable("id") String id,Model model){
		List<MemberUserDO> memberList = memberUserService.getUpUser(id);
		MemberUserDO fatherUser = new MemberUserDO();
		if(memberList.size()>0){
			fatherUser=memberList.get(0);
		}
		model.addAttribute("fatherUser", fatherUser);
		model.addAttribute("userId", id);
		return "wx/memberUser/getUpUser";
	}

	//跳转我的团队页面
	@GetMapping("/getTeam/{id}")
	String getGoods(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/team";
	}
	@ResponseBody
	@GetMapping("/getTeamInfo")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getTeamInfo(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getMyFansH(query);
		int total = memberUserService.getMyFansHCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	//跳转个人消费记录页面
	@GetMapping("/getShopping/{id}")
	String getShopping(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);

		model.addAttribute("userId", userId);
		return "wx/memberUser/shopping";
	}
	@ResponseBody
	@GetMapping("/getShoppingList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}
	//跳转统计个人消费记录页面
	@GetMapping("/orderCensus/{id}")
	String orderCensus(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);
		
		model.addAttribute("userId", userId);
		return "wx/memberUser/orderCensus";
	}
	@ResponseBody
	@GetMapping("/getOrderCensus")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getOrderCensus(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getOrderCensus(query);
		int total = memberUserService.getCountOrderCensus(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/**
	 * 导出个人消费记录excel表格
	 */
	@RequestMapping( "/getShoppingExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void getShoppingExcel(@RequestParam() Map<String,Object> params,
							  HttpServletResponse response,HttpServletRequest request){
		try
		{
			String userId = params.get("userId").toString();
			String name = memberUserService.get(userId).getName();
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+"消费记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	//跳转平台收入记录页面
	@GetMapping("/getPTShopping")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	String getPTShopping( Model model) {
//		UserDO userDO = userService.get(userId);
		return "wx/memberUser/ptShopping";
	}
	@ResponseBody
	@GetMapping("/getPTShoppingList")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public PageUtils getPTShoppingList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberUserService.getShoppingList(query);
		if(memberUserList.size()>0){
			for (Map<String, Object> map : memberUserList) {
				Map<String, Object> stoMap = new HashMap<>();
				stoMap.put("orderId", map.get("id").toString());
				stoMap.put("delFlag", "0");
				List<MemberStockDO> list = memberStockService.list(map);
				if(list.size()>0){
					MemberUserDO memberUserDO = memberUserService.get(list.get(0).getUserId());
					map.put("upName", memberUserDO.getName());
				}else{
					map.put("upName", "平台");
				}
			}
		}
		int total = memberUserService.getShoppingListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	/*
	* 平台收入总额
	* */
	@RequestMapping( "/getShoppingNum")
	@ResponseBody
	public R getShoppingNum(@RequestParam Map<String,Object> params){
		BigDecimal shoppingNum = memberUserService.getShoppingNum(params);
		return R.ok().put("data",shoppingNum);
	}

	/**
	 * 导出平台收入记录excel表格
	 */
	@RequestMapping( "/getPTShoppingExcel")
	@RequiresPermissions("wx:ptShopping:ptShopping")
	public void getPTShoppingExcel(@RequestParam() Map<String,Object> params,
								 HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.用户余额记录
			List<Map<String,Object>> list = memberUserService.getShoppingList(params);
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(("平台收入记录.xls").getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			memberUserService.shoppingExportExcel(params, list, outputStream, request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	//跳转个人积分记录页面
	@GetMapping("/getScore/{id}")
	String getScore(@PathVariable("id") String userId, Model model) {
//		UserDO userDO = userService.get(userId);
		model.addAttribute("userId", userId);
		return "wx/memberUser/score";
	}
	@ResponseBody
	@GetMapping("/getScoreList")
	@RequiresPermissions("wx:memberUser:memberUser")
	public PageUtils getScoreList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> memberUserList = memberScoreService.getScoreList(query);
		int total = memberScoreService.getScoreListCount(query);
		PageUtils pageUtils = new PageUtils(memberUserList, total);
		return pageUtils;
	}

	//修改等级页面
	@GetMapping("/editLevel/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String editLevel(@PathVariable("id") String id,Model model){
		//获取用户信息
		MemberUserDO userDO = memberUserService.get(id);
		model.addAttribute("userDO", userDO);
		return "wx/memberUser/editLevel";
	}
	//发送优惠券页面
	@GetMapping("/postCoupon/{id}")
	@RequiresPermissions("wx:memberUser:edit")
	String postCoupon(@PathVariable("id") String id,Model model){
		//获取用户信息
		MemberUserDO userDO = memberUserService.get(id);
		model.addAttribute("memberUserDO", userDO);
		return "wx/memberUser/post_coupon";
	}
	
	/*
	 * 修改用户优惠券
	 */
	@ResponseBody
	@PostMapping("/updateMemberCoupon")
	public R updateMemberCoupon(MemberCouponDO memberCouponDO) {
		if(!memberCouponDO.getCouponId().equals("-1")){
			SalesCouponDO salesCouponDO = salesCouponService.get(memberCouponDO.getCouponId());
			memberCouponDO.setCouponMoney(salesCouponDO.getEnoughMoney());
			memberCouponDO.setCouponName(salesCouponDO.getName());
			memberCouponDO.setCreateAt(new Date());
			memberCouponDO.setDelFlag(0);
			memberCouponDO.setId(UUIDUtils.getUUID());
			memberCouponDO.setMoney(salesCouponDO.getMoney());
			memberCouponDO.setStatus(0);
			memberCouponDO.setType(salesCouponDO.getType());
			memberCouponDO.setWay(1);
			memberCouponService.save(memberCouponDO);
			salesCouponDO.setSendNum(salesCouponDO.getSendNum()+1);
			salesCouponDO.setUpdateAt(new Date());
			salesCouponService.update(salesCouponDO);
			return R.ok();
		}
		
		return  R.ok();
	}

	/**
	 * 修改用户等级
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/updateLevel")
	public R updateLevel(MemberUserDO userDO) {
		return memberUserService.updateLevel(userDO);
	}
	
	
	/**
	 * 导出用户excel表格
	 */
	@RequestMapping( "/exportExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void exportExcel(@RequestParam("level") String level,
							HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.查找用户列表
			Map<String, Object> map = new HashMap<>();
			map.put("level", level);
			map.put("delFlag", "0");
			map.put("sort", "create_at");
			map.put("order", "desc");
			List<MemberUserDO> list = memberUserService.list(map);
			List<Map<String, Object>> userList= new ArrayList<>();
			if(list.size()>0){
				for (MemberUserDO memberUserDO : list) {
					map.put("userId", memberUserDO.getId());
					Map<String,Object> moneyMap = orderComService.getMemberCom(map);
	    			memberUserDO.setMoney(new BigDecimal(moneyMap.get("allPrice").toString()));
	    			BigDecimal shoppingNum = memberUserService.getShoppingNum(map);
	    			Map<String,Object> userMap = StringUtils.entityToMap(memberUserDO);
	    			userMap.put("shoppingNum", shoppingNum);
	    			MemberUserDO memberUserDO2 = memberUserService.get(memberUserDO.getIntroUser());
	    			if(memberUserDO2!=null){
	    				userMap.put("upName", memberUserDO2.getName());
	    				userMap.put("upPhone", memberUserDO2.getPhone());
	    			}else{
	    				userMap.put("upName", "");
	    				userMap.put("upPhone", "");
	    			}
	    			userList.add(userMap);
				}
			}
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("会员信息列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			UserExcelUtils.exportUserExcel(userList, outputStream);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	private String prefix="wx/memberUser"  ;


	@GetMapping("/tree/{id}")
	@ResponseBody
	public Tree<MemberUserDO> tree(@PathVariable("id") String userId) {
		//String[] split = userId.split("&");
		Tree<MemberUserDO> tree = new Tree<MemberUserDO>();
		tree = memberUserService.getTree(userId);
		return tree;
	}
	//选择直推人
	@GetMapping("/treeView/{id}")
	String treeView(Model model,@PathVariable("id") String userId) {

		model.addAttribute("userId",userId);
		return  prefix+"/deptTree";
	}


	/*
	 * 去会员订单详细信息页面
	 * */
	@GetMapping("/goMemberDetails/{id}")
	@RequiresPermissions("beaut:memberUser:memberUser")
	public String goMemberDetails(@PathVariable("id") String id,Model model){
		model.addAttribute("userId", id);
		return "wx/memberUser/memberDetails";
	}

	@ResponseBody
	@RequestMapping("/getMemberDetails")
	@RequiresPermissions("beaut:memberUser:memberUser")
	public R getMemberDetails(@RequestParam Map<String, Object> params){
		String userId = params.get("userId").toString();
		MemberUserDO userDO = memberUserService.get(userId);
		Date sTime = null;
		Date eTime = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Object sTimeObject = params.get("sTime");
			if (sTimeObject == null || "".equals(sTimeObject.toString())) {
				sTime = userDO.getCreateAt();
			} else {
				sTime = simpleDateFormat.parse(params.get("sTime").toString());
			}
			Object eTimeObject = params.get("eTime");
			if (eTimeObject == null || "".equals(eTimeObject.toString())) {
				eTime = new Date();
			} else {
				eTime = simpleDateFormat.parse(params.get("eTime").toString());
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String startTime = DateUtils.getTable(sTime);
		String endTime = DateUtils.getTable(eTime);
		List<String> ptTimeList = DateUtils.getTableBetween(startTime, endTime);//月份集合
		BigDecimal mineNum = new BigDecimal(0);
		BigDecimal mineMoney = new BigDecimal(0);
		BigDecimal tprice = new BigDecimal(0);
		BigDecimal toNumber = new BigDecimal(0);
		BigDecimal tgNumber = new BigDecimal(0);
		BigDecimal gprice = new BigDecimal(0);
		BigDecimal goNumber = new BigDecimal(0);
		BigDecimal ggNumber = new BigDecimal(0);
		for (String ptTime : ptTimeList) {
			params.put("tableName",ptTime);
			Map<String,Object> orderMap = orderOrderService.getOrderDetails(params);
			mineNum = mineNum.add(new BigDecimal(orderMap.get("mineNum").toString()));
			mineMoney = mineMoney.add(new BigDecimal(orderMap.get("mineMoney").toString()));
			Map<String,Object> tuanMap = memberUserService.getTeamDetails(params);
			tprice = tprice.add(new BigDecimal(tuanMap.get("allPrice").toString()));
			toNumber = toNumber.add(new BigDecimal(tuanMap.get("orderNumber").toString()));
			tgNumber = tgNumber.add(new BigDecimal(tuanMap.get("goodNumber").toString()));
			params.put("tp","0");
			Map<String,Object> geMap = memberUserService.getTeamDetails(params);
			gprice = gprice.add(new BigDecimal(geMap.get("allPrice").toString()));
			goNumber = goNumber.add(new BigDecimal(geMap.get("orderNumber").toString()));
			ggNumber = ggNumber.add(new BigDecimal(geMap.get("goodNumber").toString()));

		}

		//自己下单数据
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("mineNum",mineNum);
		map.put("mineMoney",mineMoney);
		map.put("tprice",tprice);
		map.put("toNumber",toNumber);
		map.put("tgNumber",tgNumber);
		map.put("gprice",gprice);
		map.put("goNumber",goNumber);
		map.put("ggNumber",ggNumber);
		return R.ok().put("data",map);
	}
	
}
